<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="500px" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #menu="{ model, field }">
        <BasicTree v-model:value="model[field]" :treeData="treeData" @check='fatherRelateChild' checkStrictly=false
          :checkedKeys="checkedRow" :fieldNames="{ title: 'meta.title', key: 'id' }" checkable toolbar title="菜单分配" />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>

<script lang="ts" setup>
import { ref, computed, unref } from 'vue'
import { BasicForm, useForm } from '@/components/Form'
import { formSchema } from './role.data'
import { BasicDrawer, useDrawerInner } from '@/components/Drawer'
import { BasicTree, TreeItem } from '@/components/Tree'
import { addOrUpdateRole, getRoleDetail } from '@/api/sys/role'
import backMenus from '@/settings/backMenus'

const emit = defineEmits(['success', 'register'])
const isUpdate = ref(true)
const treeData = ref<TreeItem[]>([])
const recordRef = ref()
const checkedRow = ref<any>([])
// console.log(backMenus)
const reProduceData = (data: any[]) => {
  let result: any[] = []
  data.map((item) => {
    let newItem: any = {
      resourceId: item.resourceId,
      resourceName: item.resourceName,
      orderNo: item.sortNo,
      type: item.resourceType,
      children: [],
    }
    if (item.children.length) {
      const newData = reProduceData(item.children)
      newItem.children = newData
    }
    result.push(newItem)
  })
  return result
}

const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 90,
  baseColProps: { span: 24 },
  schemas: formSchema,
  showActionButtonGroup: false,
})

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  resetFields()
  setDrawerProps({ confirmLoading: false })
  // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
  if (unref(treeData).length === 0) {
    // treeData.value = (menuList) as any as TreeItem[]
    // const ret = await getResourceTree()
    // const formateRet = reProduceData(ret)
    treeData.value = backMenus as any as TreeItem[]
    console.log(backMenus);

    // treeData.value = formateRet as any as TreeItem[]
  }
  isUpdate.value = !!data?.isUpdate
  if (unref(isUpdate)) {
    setFieldsValue({
      ...data.record,
    })
    recordRef.value = await getRoleDetail(data.record.roleId)
    checkedRow.value = recordRef.value.resourceIdList || []
    // checkedRow.value = recordRef.value.resourceIdList || []
  }
})

const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'))

const fatherRelateChild = (checkedKeys, info) => {
  const { checked } = checkedKeys;
  const { node } = info;

  // 如果有子级，向下查找所有子级ids
  // if (node.children) {
  //   const childIds = findChildIds(info.node)
  //   const selectChildKeys = new Set([...checked, ...childIds])
  //   checkedRow.value = Array.from(selectChildKeys.values());
  //   console.log('father relate child', checked, info, selectChildKeys);
  // }

  // 如果有父级，则向上查找所有父级ids
  if (node.parent) {
    const parentIds = findParentIds(info.node)
    const selectKeys = new Set([...checked, ...parentIds])
    checkedRow.value = Array.from(selectKeys.values());
  }
}

const findParentIds = (treeData, ids: any = []) => {
  if (treeData.parent) {
    ids.push(treeData.parent.node.id);
    findParentIds(treeData.parent, ids)
  }
  return ids;
}

const findChildIds = (treeData, ids: any = []) => {
  for (let i = 0; i < treeData.children.length; i++) {
    ids.push(treeData.children[i].id);
    if (treeData.children[i].children) {
      findChildIds(treeData.children[i].children, ids)
    }
  }
  return ids;
}

async function handleSubmit() {
  try {
    const values = await validate()
    setDrawerProps({ confirmLoading: true })
    const params = { ...values, resourceIdList: Array.from(values?.resourceIdList?.checked || values?.resourceIdList || []) }
    const apiParams = unref(isUpdate) ? { ...params, roleId: recordRef.value.roleId } : params
    const res = await addOrUpdateRole(apiParams)
    res && emit('success')
    closeDrawer()
  } finally {
    setDrawerProps({ confirmLoading: false })
  }
}
</script>
